package com.woniushop.service.imple;

import java.util.List;

import com.woniushop.dao.GoodsDAO;
import com.woniushop.dao.OrderInfoDAO;
import com.woniushop.dao.imple.GoodsDAOImple;
import com.woniushop.dao.imple.OrderInfoDAOImple;
import com.woniushop.entity.Goods;
import com.woniushop.entity.OrderInfo;
import com.woniushop.service.OrderInfoService;

/**
 * 订单明细业务逻辑接口的实现类
 * 
 * @author 崔新雄
 *
 */
public class OrderInfoServiceImple implements OrderInfoService {

	private OrderInfoDAO orderInfoDAO = new OrderInfoDAOImple();
	private GoodsDAO goodsDAO = new GoodsDAOImple();

	/**
	 * 增加订单明细
	 * 
	 * @param orderInfo
	 */
	@Override
	public void add(OrderInfo orderInfo) {
		OrderInfo one = orderInfoDAO.findOne(orderInfo.getOid(), orderInfo.getGid());
		if (one != null) {
			one.setOinum(one.getOinum() + orderInfo.getOinum());
			one.setOiprice(orderInfo.getOiprice());// 购物车中的价格要随时变化
			orderInfoDAO.update(one);
		} else {
			orderInfoDAO.add(orderInfo);
		}
	}

	/**
	 * 根据订单id返回该订单所有明细
	 * 
	 * @param oid
	 * @return
	 */
	@Override
	public List<OrderInfo> findAll(Integer oid) {
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setOid(oid);

		Integer pageSize = orderInfoDAO.count(orderInfo);

		return orderInfoDAO.findByPage(1, pageSize, orderInfo);
	}

	/**
	 * 根据订单明细id返回该订单明细对象
	 * 
	 * @param oiid
	 * @return
	 */
	@Override
	public OrderInfo finOne(Integer oiid) {
		return orderInfoDAO.findOne(oiid);
	}

	/**
	 * 修改订单明细
	 * 
	 * @param orderInfo
	 */
	@Override
	public void update(OrderInfo orderInfo) {
		orderInfoDAO.update(orderInfo);
	}

	/**
	 * 批量删除订单明细
	 * 
	 * @param oiids
	 */
	@Override
	public void delAll(String[] oiidsStr) {
		Integer[] oiids = new Integer[oiidsStr.length];
		for (int i = 0; i < oiids.length; i++) {
			oiids[i] = Integer.parseInt(oiidsStr[i]);
		}
		orderInfoDAO.deleteAll(oiids);
	}

	/**
	 * 生成新的订单明细
	 * 
	 * @param orderInfo
	 * @return
	 */
	@Override
	public OrderInfo addNewOrderInfo(OrderInfo orderInfo) {
		Integer oid = orderInfo.getOid();
		Integer gid = orderInfo.getGid();
		Goods goods = goodsDAO.findOne(gid);
		orderInfo.setOiprice(goods.getGprice());
		orderInfoDAO.add(orderInfo);
		return orderInfoDAO.findOne(oid, gid);
	}

	/**
	 * 将一组订单明细加入都某一订单中
	 * 
	 * @param oiids
	 * @param oid
	 */
	@Override
	public void toOrder(String[] oiids, Integer oid) {
		for (int i = 0; i < oiids.length; i++) {
			OrderInfo orderInfo = orderInfoDAO.findOne(Integer.parseInt(oiids[i]));
			orderInfo.setOid(oid);
			orderInfoDAO.update(orderInfo);
		}
	}

	/**
	 * 删除某订单下的所有订单明细
	 * 
	 * @param oid
	 */
	@Override
	public void deleteByOid(Integer oid) {
		orderInfoDAO.deleteByOid(oid);
	}
}
